package demo17_SinglePattern;

/**
 * @author kunkun
 * @className Test02_Lazy_common
 * @Description 单例模式---懒汉式---展示问题（多线程出现故障）
 * @date 2025/3/8 13:12
 */
public class Test03_Lazy_problem {

    private volatile static Test03_Lazy_problem hungry ;//避免指令重排，加上Volatile

    public Test03_Lazy_problem(){
        System.out.println(hungry);
    }

    public static Test03_Lazy_problem getInstance(){
        if (hungry==null){
            synchronized (Test03_Lazy_problem.class){
                if (hungry==null){
                    hungry = new Test03_Lazy_problem();
                }
            }
        }
        return hungry;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            new Thread(()->{
                Test03_Lazy_problem.getInstance();
            }).start();
        }
        while (Thread.activeCount()>2){
            Thread.yield();
        }
    }
}
